package cn.xyafu.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.xyafu.po.Lost;
import cn.xyafu.po.Page;
import cn.xyafu.po.Tlt;
import cn.xyafu.po.User;
import cn.xyafu.service.LostService;
import cn.xyafu.service.TLTService;

@Controller
@Transactional
public class LostController {
    @Autowired
    private LostService lostService;
    @Autowired
    private TLTService tltService;

    /**
     * 分页查询所有失物信息(所有，分类，关键字)
     */
    @RequestMapping("/allLost")
    public String findAllLost(String keyWord, HttpSession session, HttpServletRequest req, Model model) {
        String action = req.getParameter("action");
//        System.out.println(action);
        //action为空，则默认为all
        if (action == null){
            action = "all";
        }
        String type = (String) session.getAttribute("type");
        String cType = req.getParameter("tid");
        Page page = (Page) req.getSession().getAttribute("page");
        //记录搜索类型
        int tp = 1;
        if (type != null) {
            tp = Integer.parseInt(type);
        }
        if (cType != null && !cType.equals("all")) {
            tp = Integer.parseInt(cType);
        }
        //标记是否切换关键字
        boolean flag = false;
        //关键字切换
        if (keyWord != session.getAttribute("keyWord") && keyWord != "" && keyWord !=null) {
            session.setAttribute("keyWord", keyWord);
            flag = true;
        } else if (keyWord == session.getAttribute("keyWord")) {

        } else if ("search".equals(req.getParameter("search")) ){
            session.setAttribute("keyWord", "");
            flag = true;
        } else{
            session.setAttribute("keyWord", "");
        }
        if (page == null || cType != null || flag) {      //首次点开或切换分类
            page = new Page(1, 5);
            if ("all".equals(action)) {
                page.setTotal(this.lostService.countLost(keyWord));
            } else if ("type".equals(action)) {
                page.setTotal(this.lostService.countLostByType(tp));
            }
        } else {
            String str = req.getParameter("set");       //获取翻页操作
            int nowPage = page.getStart();              //当前页码
            if ("add".equals(str)) {                 //下一页
                if (page.isHasNext()) {          //已是尾页

                } else {
                    page.setStart(nowPage + 1);
                }
            } else if ("sub".equals(str)) {           //上一页
                if (!page.isHasPreviouse()) {             //已是首页

                } else {
                    page.setStart(nowPage - 1);
                }
            } else if ("top".equals(str)) {           //首页
                page.setStart(1);
            } else if ("bottom".equals(str)) {        //尾页
                page.setStart(page.getTotalPage());
            }
        }

        List<Lost> losts = null;

        Integer start = (page.getStart() - 1) * page.getCount();
        Integer end = page.getCount();

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("type", tp);
        map.put("keyWord", keyWord);
        map.put("start", start);
        map.put("end", end);

        if ("all".equals(action)) {
            losts = this.lostService.findAllLost(map);
        } else if ("type".equals(action)) {
            losts = this.lostService.findByType(map);
        }
        session.setAttribute("losts", losts);
        session.setAttribute("page", page);
        session.setAttribute("type", String.valueOf(tp));
        session.setAttribute("keyWord", keyWord);
        req.setAttribute("action", action);

        return "/WEB-INF/index";
    }

    /**
     * 查看失物详情
     */
    @RequestMapping("/showLost")
    public String findLostById(HttpSession session,String lostId,String cpage){
        if (cpage != "" && cpage!= null && cpage.equals("cpage")){
            session.removeAttribute("comment_page");
        }
        Integer lid = Integer.parseInt(lostId);
        Lost lost = this.lostService.findByLid(lid);
        session.setAttribute("onelost",lost);
        return "forward:allComments";
    }

    /**
     * 发布失物信息
     */
    @RequestMapping("/addLost")
    public void addLost(@RequestParam("ltitle") String ltitle, @RequestParam("lmsg") String lmsg, @RequestParam("type") String type, @RequestParam("limg") MultipartFile limg, HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        User user = (User) session.getAttribute("USER_SESSION");
        //获取上传文件的原始名称
        String originalFilename = limg.getOriginalFilename();
        //设置上传文件的保存地址目录
        String dirPath = request.getServletContext().getRealPath("/img/");
        File filePath = new File(dirPath);
        //如果保存文件的地址不存在，就先创建目录
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        //使用uuid重新命名上传的文件名称（上传人_uuid_原始文件名称）
        String newFilename = user.getUnikename()+"_"+ UUID.randomUUID()+"_"+originalFilename;
        try {
            //使用MultipartFile接口的方法完成文件上传到指定位置
            limg.transferTo(new File(dirPath+newFilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将信息存入数据库
        Lost lost = new Lost();
        lost.setLtitle(ltitle);
        lost.setLmsg(lmsg);
        lost.setLimg("img/"+newFilename);
        SimpleDateFormat sdf =   new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        lost.setLdate(sdf.format(new Date()));
        lost.setUser(user);
        this.lostService.addByLost(lost);
        //获取多选框中的分类信息
        String[] types = type.split(",");
        Tlt tlt = new Tlt();
        //遍历插入映射信息到映射表t_tlt中
        for (String str : types){
            Integer s = Integer.parseInt(str);
            tlt.setLid(lost.getLid());
            tlt.setTid(s);
            tltService.addTLT(tlt);
        }
        response.getWriter().print("<script>alert('信息已发布！');window.location.href='/Lost_ssm/my.jsp'</script>");
    }

    /**
     * 查看个人已发布信息
     */
    @RequestMapping("/userLost")
    public String findUserLost(HttpSession session){
        User user = (User) session.getAttribute("USER_SESSION");
        List<Lost> losts = lostService.findByUid(user.getUid());
        session.setAttribute("losts", losts);
        return "redirect:my.jsp?my_action=publish";
    }

    /**
     * 删除lost（lid）
     */
    @RequestMapping("/deleteLost")
    public String deleteLost(String lid,HttpSession session){
        //封装uid,lid
        Lost lost = new Lost();
        lost.setUser((User)session.getAttribute("USER_SESSION"));
        lost.setLid(Integer.parseInt(lid));
        this.lostService.deleteByLost(lost);
        return "forward:userLost";
    }


}
